Leetcode JS 2627. Debounce


Posted by Lucy on 2023-06-05

其實應該先寫Debounce再寫Throttle,不過因為Throttle花比較久時間所以先寫。

var debounce = function(fn, t=500) {
    let timer=null;
    return function(...args) {
        clearTimeout(timer)
        timer=setTimeout(()=>{fn.apply(this,args)},t)
    }
}

上面這段算是最簡單的debounce,可以根據需求再做擴展,比較有名的debounce大概就lodash的debounce吧,剛好最近有遇到一個覺得用Debounce很適合的需求。
需求為當網頁閒置一段時間後,就要自動登出,閒置的定義為滑鼠沒有移動來做偵測

        let delayTime = 分 * 60 * 1000;
        const timeout = debounce(() => {
            //...logout處理
        }, delayTime);
        document.body.addEventListener('mousemove', timeoutFn);
        //記得登出前要把事件取消掉

因為滑鼠事件會一直移動,感覺再加個Throttle做限制好像也行,目前簡易登出偵測大概就這樣,有想到再來補充。


#Leetcode







Related Posts

Day05 - CSS色彩、背景與漸層

Day05 - CSS色彩、背景與漸層

week4 作業繳交!

week4 作業繳交!

CSS 衍生的資安問題(中) - 不用 Hot Update 也行

CSS 衍生的資安問題(中) - 不用 Hot Update 也行


Comments